<?php

/**
 * Framework_Util_DbAuthenticator
 *
 *
 * @author Application Support Group
 * @copyright University of Georgia
 * @package BAMF
*/
class Framework_Util_DbAuthenticator extends Framework_Util_Authenticator {

	private $_authClass ;
	private $_usernameAttribute ;
	private $_passwordAttribute ;
	private $_passwordEncryptionMethod ;




	public function __construct( 
		$anAuthClass=DB_AUTHENTICATION_CLASS, 
		$userAttr=DB_AUTH_USER_ATTR, 
		$passwdAttr=DB_AUTH_PASS_ATTR, 
		$encryptionMethod="SHA1" ,
		$theDsn=FRAMEWORK_DSN
	) {


		parent::__construct( $theDsn );

		if( empty( $anAuthClass )) {
			$error = Framework_ErrorHandler::raiseError( "DB_AUTHENTICATION_CLASS is not properly defined.", __METHOD__."::".__LINE__ ) ;
			die( $error->getMessage() ) ;
		} else {
			$this->_authClass = $anAuthClass ;
			$this->_usernameAttribute = $userAttr ;
			$this->_passwordAttribute = $passwdAttr ;
			$this->_passwordEncryptionMethod = $encryptionMethod ;
		}

	}// end constructor




/**
 * authenticate()
 *
 * @param               string $aUsername 
 * @param               string $aPassword 
 * @param               array $returnAttributes 
 *
 * @return              mixed Array of attributes on success, PEAR Error on failure.
 *
 * @package BAMF
 * @subpackage Framework_Util
 * 
*/
	public function authenticate( $aUsername, $aPassword, $returnAttributes=array() ) {

		$_output = false ;
		$aUsername = trim( $aUsername ) ;
		$aPassword = trim( $aPassword ) ;

		if( !empty( $aUsername )) {
			if( !empty( $aPassword )) {

				$thePassword = null ;

				switch( $this->_passwordEncryptionMethod ) {
					case "MD5" :
						$thePassword = md5( $aPassword ) ;
						break ;
	
					case "SHA1" :
					default:
						$thePassword = sha1( $aPassword ) ;
						break ;
				}

				$userWhere = array() ;
				$userWhere[] = "{$this->_usernameAttribute}='$aUsername'" ;
				$userWhere[] = "{$this->_passwordAttribute}='$thePassword'" ;
				$theUserParams = new Framework_DB_DaoParameters( array( 'where'=>$userWhere )) ; 
				$theUser = Framework_DB_DaoNodeFactory::build( $this->_authClass, $theUserParams ) ;

				if( !Framework_ErrorHandler::isError( $theUser )) {
					$_output = true ;
				} else {
					$_output = $theUser ;
				}

			} else {
				$_output = Framework_ErrorHandler::raiseError( "Password is required input.", __METHOD__."::".__LINE__ ) ;
			}
		} else {
			$_output = Framework_ErrorHandler::raiseError( "Username is required input.", __METHOD__."::".__LINE__ ) ;
		}

		return $_output ;


	}// end authenticate()


	public function __destruct() {
		parent::__destruct();
	}
}

?>
